package com.bieyang.anjia.ui.activity;

import java.util.ArrayList;
import java.util.List;

import org.webrtc.mqttclientsample.MessageService;
import org.webrtc.ui.VideoUI;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.BitmapFactory.Options;
import android.graphics.Color;
import android.graphics.Matrix;
import android.graphics.PointF;
import android.graphics.RectF;
import android.media.MediaMetadataRetriever;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
import android.media.MediaPlayer.OnErrorListener;
import android.net.Uri;
import android.os.Environment;
import android.os.Handler;
import android.os.IBinder;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.util.DisplayMetrics;
import android.util.FloatMath;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.ImageView.ScaleType;
import android.widget.LinearLayout;
import android.widget.MediaController;
import android.widget.TextView;
import android.widget.VideoView;
import com.bieyang.anjia.R;
import com.bieyang.anjia.module.Device;
import com.bieyang.anjia.module.FileModel;
import com.bieyang.anjia.module.LoginTypeEnum;
import com.bieyang.anjia.module.User;
import com.bieyang.anjia.net.NetManager;
import com.bieyang.anjia.sqlitedatabase.AnjiaSQLiteOpenHelper;
import com.bieyang.anjia.sqlitedatabase.SqliteOperation;
import com.bieyang.anjia.ui.adapter.AlarmPageAdapter;
import com.bieyang.anjia.utils.Constants;
import com.bieyang.anjia.utils.SharedPrefsUtil;
import com.bieyang.anjia.utils.Show;
import com.bieyang.anjia.utils.SubUtils;

/**
 * 安信详细界面
 * 
 * @author M.y.q
 * 
 */
@SuppressLint("FloatMath")
public class AcAnxinAthome extends BaseNoFlyActivity implements
		OnErrorListener, OnCompletionListener, OnClickListener {
	private MyServiceConnection conn;
	private Bitmap videoBitmap;
	// 立即查看--开启实时视频按钮
	private TextView immediatelyCheck;
	// 顶部标题 ,报警信息, 报警时间
	private TextView topLineTitle, alarmDetailedInfo, alarmDetailedTime;
	private VideoView alarmVideo;
	private int mPositionWhenPaused = -1;
	private Uri mUri;
	private ImageView startAlarmVideo, onePictureAlarm;
	// 报警类型 0-视频,1-3连拍,2-拍1张
	private int alarmCode = -1;
	private ViewPager alarmPager;
	private ImageView alarmVideoBj;
	// 文件path,采集端uuid
	private String path, uuid;
	private Context con;
	float density = 1;
	private MediaController mc;
	@SuppressLint("HandlerLeak")
	Handler handler = new Handler() {
		public void handleMessage(android.os.Message msg) {
			switch (msg.what) {
			case Constants.LOGIN_SUCESS:
				App.isLogin = true;
				Intent pubService = new Intent(con, PubService.class);
				con.startService(pubService);
				conn = new MyServiceConnection();
				Intent serviceIntent = new Intent(con, MessageService.class);
				bindService(serviceIntent, conn, BIND_AUTO_CREATE);
				MessageService.startService(con, SubUtils.getUuid(con));
				Device divice = new Device();
				divice.setMemberId(SharedPrefsUtil.getStringValue(App.mContext,
						"memberId", ""));
				App.netManager.getDev(con, divice, handler);
				break;
			case Constants.LOGIN_FAIL:
				if (null != progressDialog) {
					progressDialog.dismiss();
				}
				Show.toast(con, R.string.internet_exception);
				break;
			default:
				break;
			}
		};
	};

	/**
	 * 登录
	 * 
	 * @param con
	 */
	private void login(Context con) {
		App.mContext = getApplicationContext();
		String phone = SharedPrefsUtil.getStringValue(con, "phone", null);
		String password = SharedPrefsUtil.getStringValue(con, "password", null);
		String uuid = SubUtils.getUuid(con);
		if (null != phone && null != password) {
			User user = new User();
			user.setCardNo(phone);
			user.setPassword(password);
			user.setUuid(uuid);
			user.setType(LoginTypeEnum.MAIN);
			SharedPrefsUtil.putValue(App.mContext, "loginType", "M");
			App.netManager.login(con, user, handler);
		}
	}

	@Override
	void setContent() {
		setContentView(R.layout.anxin_athome);
		App.newNews = false;
		con = AcAnxinAthome.this;
		SubUtils.clearNotification(con);
		DisplayMetrics dm = new DisplayMetrics();
		dm = getApplicationContext().getResources().getDisplayMetrics();
		density = dm.density;
	}

	private class MyServiceConnection implements
			android.content.ServiceConnection {

		@Override
		public void onServiceConnected(ComponentName name, IBinder service) {
		}

		@Override
		public void onServiceDisconnected(ComponentName name) {
		}

	}

	@Override
	void initView() {
		Intent intent = getIntent();
		alarmCode = intent.getIntExtra("alarmMethods", -1);
		String time, type, name;

		if (intent.getBooleanExtra("formNotification", false)) {
			Log.d("alarmCode", alarmCode + "");
			if (!App.isLogin) {
				login(con);
			}
			alarmCode = SharedPrefsUtil.getIntValue(con, "alarmCode", -1);
			name = SharedPrefsUtil.getStringValue(con, "alarmName", "");
			type = SharedPrefsUtil.getStringValue(con, "alarmType", "");
			uuid = SharedPrefsUtil.getStringValue(con, "alarmUuid", "");
			path = SharedPrefsUtil.getStringValue(con, "alarmPath", "");
			time = SharedPrefsUtil.getStringValue(con, "alarmTime", "");
		} else {
			Log.d("alarmCode", alarmCode + "");
			FileModel model = (FileModel) intent.getSerializableExtra("model");
			time = model.time;
			type = model.alarmType;
			name = model.name;
			uuid = model.uuid;
			path = model.filePath;
		}
		SqliteOperation sqlOperation = new SqliteOperation(con,
				AnjiaSQLiteOpenHelper.dbName, AnjiaSQLiteOpenHelper.version);
		sqlOperation.update("alarminfo", "alarmtime = ? and uuid = ?",
				new String[] { time, uuid }, "isnew", "T");
		if (!Environment.getExternalStorageState().equals(
				Environment.MEDIA_MOUNTED)
				&& alarmCode == 0) {
			Show.toast(con, "no sdcard!");
			alarmCode = -1;
		}
		Log.d("test", "alarmCode=" + alarmCode + "\nuuid=" + uuid + "\npath="
				+ path + "\ntime=" + time + "\ntype=" + type + "\nname=" + name);
		alarmDetailedTime = (TextView) findViewById(R.id.alarmDetailedTime);
		alarmDetailedTime.setText(time);
		alarmDetailedInfo = (TextView) findViewById(R.id.alarmDetailedInfo);
		alarmDetailedInfo.setText(name + ":" + type);
		immediatelyCheck = (TextView) findViewById(R.id.immediately_check);
		immediatelyCheck.setOnClickListener(this);

		topLineTitle = (TextView) findViewById(R.id.topLineTitle);
		topLineTitle.setText(getString(R.string.detailed_alarm));
		alarmPager = (ViewPager) findViewById(R.id.alarmViewPager);
		onePictureAlarm = (ImageView) findViewById(R.id.onePictureAlarm);
		LinearLayout threeAlarmLL = (LinearLayout) findViewById(R.id.threeAlarmLL);
		switch (alarmCode) {
		case 0:
			threeAlarmLL.setVisibility(View.GONE);
			onePictureAlarm.setVisibility(View.GONE);
			initVideoView();
			break;
		case 1:
			onePictureAlarm.setVisibility(View.GONE);
			initThreePhoto();
			break;
		case 2:
			// 报警图片
			// onePictureAlarm.setImageURI(Uri.parse(path));
			initImage(path, onePictureAlarm);
			break;
		default:
			break;
		}
	}

	void initThreePhoto() {
		String path[] = this.path.split(";");
		Log.d("path", path[0]);
		Log.d("path", path[1]);
		Log.d("path", path[2]);
		List<View> list = new ArrayList<View>();
		ImageView img0 = new ImageView(this);
		img0.setLayoutParams(new ViewGroup.LayoutParams(
				ViewGroup.LayoutParams.MATCH_PARENT,
				ViewGroup.LayoutParams.MATCH_PARENT));
		img0.setScaleType(ScaleType.MATRIX);
		// 报警第1张图片
		initImage(path[0], img0);
		list.add(img0);
		ImageView img1 = new ImageView(this);
		img1.setLayoutParams(new ViewGroup.LayoutParams(
				ViewGroup.LayoutParams.MATCH_PARENT,
				ViewGroup.LayoutParams.MATCH_PARENT));
		img1.setScaleType(ScaleType.MATRIX);
		// 报警第2张图片
		initImage(path[1], img1);
		list.add(img1);
		ImageView img2 = new ImageView(this);
		img2.setLayoutParams(new ViewGroup.LayoutParams(
				ViewGroup.LayoutParams.MATCH_PARENT,
				ViewGroup.LayoutParams.MATCH_PARENT));
		img2.setScaleType(ScaleType.MATRIX);
		// 报警第3张图片
		initImage(path[2], img2);
		list.add(img2);
		ImageView first = (ImageView) findViewById(R.id.firstPage);
		ImageView second = (ImageView) findViewById(R.id.secondPage);
		ImageView third = (ImageView) findViewById(R.id.thirdPage);
		final ImageView[] imgs = { first, second, third };
		alarmPager.setAdapter(new AlarmPageAdapter(list));
		alarmPager.setOnPageChangeListener(new OnPageChangeListener() {

			@Override
			public void onPageSelected(int arg0) {
				for (int i = 0; i < imgs.length; i++) {
					if (arg0 == i) {
						imgs[i].setImageResource(R.drawable.change_dot_checked);
					} else {
						imgs[i].setImageResource(R.drawable.change_dot_unchecked);
						Matrix matrix = new Matrix();
						matrix.setScale(density, density); // 开始先缩小
						// matrix.postTranslate(120, 120); //
						// 图片的位置相对于imageview的左上角往右往下各偏移120个像素
						imgs[i].setImageMatrix(matrix);
					}
				}
			}

			@Override
			public void onPageScrolled(int arg0, float arg1, int arg2) {
			}

			@Override
			public void onPageScrollStateChanged(int arg0) {
			}
		});
	}

	/**
	 * 解码图片
	 * 
	 * @param path
	 *            本地路径
	 * @param view
	 *            显示控件
	 */
	void initImage(String path, ImageView view) {
		Options option = new Options();
		option.inJustDecodeBounds = true;
		BitmapFactory.decodeFile(path, option);
		int inSampleSize = option.outWidth / 320;
		option.inSampleSize = inSampleSize;
		Log.d("inSampleSize ", option.inSampleSize + "");
		option.inJustDecodeBounds = false;
		Bitmap bitmap = BitmapFactory.decodeFile(path, option);
		bitmap = Bitmap.createScaledBitmap(bitmap, 320, 262, true);
		view.setImageBitmap(bitmap);
		view.setOnTouchListener(new MyOntouch(con, view, bitmap, density));
	}

	void initVideoView() {
		alarmPager.setVisibility(View.GONE);
		alarmVideo = (VideoView) findViewById(R.id.alarm_video);
		startAlarmVideo = (ImageView) findViewById(R.id.startAlarmVideo);
		startAlarmVideo.setVisibility(View.VISIBLE);
	}

	@Override
	void initData() {
		if (0 == alarmCode) {
			initVideoData();
		}
	}

	/**
	 * 视频播放器设置
	 */
	void initVideoData() {
		// 报警视频uri
		mc = new MediaController(con);
		mc.setPadding(0, 0, 0, 0);
		mc.setVisibility(View.GONE);
		mc.setBackgroundColor(Color.TRANSPARENT);
		// mc.setAlpha(0);
		// mc.setAnchorView(alarmVideo);
		alarmVideo.setMediaController(mc);
		// mc.setAnchorView(alarmVideo);
		mUri = Uri.parse(path);
		MediaMetadataRetriever media = new MediaMetadataRetriever();
		media.setDataSource(AcAnxinAthome.this, mUri);
		alarmVideoBj = (ImageView) findViewById(R.id.alarmVideoBj);
		videoBitmap = media.getFrameAtTime();
		alarmVideo.setVideoURI(mUri);
	}

	/**
	 * 设置视频播放器监听
	 */
	void setVideoListener() {
		alarmVideo.setOnErrorListener(this);
		alarmVideo.setOnCompletionListener(this);
		startAlarmVideo.setOnClickListener(this);
		alarmVideo.setOnTouchListener(new OnTouchListener() {
			@Override
			public boolean onTouch(View v, MotionEvent event) {
				return true;
			}
		});
	}

	@Override
	void setListener() {
		if (0 == alarmCode) {
			setVideoListener();
		}
		immediatelyCheck.setOnClickListener(this);
	}

	@Override
	public boolean onError(MediaPlayer mp, int what, int extra) {
		return false;
	}

	@Override
	public void onCompletion(MediaPlayer mp) {
		startAlarmVideo.setVisibility(View.VISIBLE);
	}

	@Override
	protected void onStart() {
		super.onStart();
	}

	@Override
	protected void onResume() {
		super.onResume();
		if (0 == alarmCode) {
			alarmVideoBj.setImageBitmap(videoBitmap);
			if (mPositionWhenPaused >= 0) {
				alarmVideo.seekTo(mPositionWhenPaused);
				mPositionWhenPaused = -1;
			}
			mc.setVisibility(View.GONE);
			startAlarmVideo.setVisibility(View.VISIBLE);
		}

	}

	@Override
	protected void onPause() {
		if (0 == alarmCode) {
			if (alarmVideo.isPlaying()) {
				mPositionWhenPaused = alarmVideo.getCurrentPosition();
			}
			alarmVideo.stopPlayback();
		}
		super.onPause();
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.immediately_check:
			startVideoCall();
			break;
		case R.id.startAlarmVideo:
			startAlarmVideo.setVisibility(View.GONE);
			alarmVideoBj.setImageBitmap(null);
			alarmVideo.start();
			break;
		default:
			break;
		}
	}

	/** 开启视频通话 */
	private void startVideoCall() {
		if (null == uuid || uuid.isEmpty()) {
			finish();
		} else {
			if (App.isLogin) {
				if (!"ONLINE".equals(NetManager.subOnLineMap.get(uuid))) {
					Show.toast(con, R.string.tip_live_offline);
					return;
				}
			} else {
				Show.toast(con, R.string.please_login);
				return;
			}
			VideoUI.Lauch(con, uuid, uuid, true, true, false);
		}
	}

	/**
	 * 图片缩放
	 * 
	 * @author M.y.q
	 */
	class MyOntouch implements OnTouchListener {
		private static final int NONE = 0;
		private static final int DRAG = 1;
		private static final int ZOOM = 2;

		private int mode = NONE;
		private float oldDist;
		private Matrix matrix = new Matrix();
		private Matrix savedMatrix = new Matrix();
		private PointF start = new PointF();
		private PointF mid = new PointF();
		ImageView view;
		Bitmap bitmap;
		DisplayMetrics dm;
		float minScaleR = 1f; // 最少缩放比例
		float maxScaleR = 5f; // 最大缩放比例
		float dist = 1f;

		public MyOntouch(Context context, ImageView view, Bitmap bitmap,
				float density) {
			this.view = view;
			this.bitmap = bitmap;
			minScaleR = density;
			maxScaleR = density * 5;
			dm = new DisplayMetrics();
			((Activity) context).getWindowManager().getDefaultDisplay()
					.getMetrics(dm); // 获取分辨率
			matrix.setScale(minScaleR, minScaleR); // 开始先缩小
			view.setImageMatrix(matrix);
		}

		@Override
		public boolean onTouch(View v, MotionEvent event) {
			ImageView view = (ImageView) v;
			switch (event.getAction() & MotionEvent.ACTION_MASK) {
			case MotionEvent.ACTION_DOWN: // 单点
				savedMatrix.set(matrix);
				start.set(event.getX(), event.getY());
				mode = DRAG;
				break;
			case MotionEvent.ACTION_UP: // 单点弹起
			case MotionEvent.ACTION_POINTER_UP: // 多点弹起
				mode = NONE;
				break;
			case MotionEvent.ACTION_POINTER_DOWN: // 多点
				oldDist = spacing(event);
				if (oldDist > 10f) {
					savedMatrix.set(matrix);
					midPoint(mid, event);
					mode = ZOOM;
				}
				break;
			case MotionEvent.ACTION_MOVE: // 按下且在拖动
				// if (mode == DRAG) {
				// matrix.set(savedMatrix);
				// matrix.postTranslate(event.getX() - start.x, event.getY()
				// - start.y); // xy方向都可以拖动
				// // matrix.postTranslate(event.getX() - start.x,0);
				// // //只在x轴方向拖动 即左右拖动 上下不动
				// // matrix.postTranslate(0,event.getY() - start.y);
				// // //只在y轴方向拖动 即上下拖动 左右不动
				// } else
				// if (mode == ZOOM) {
				// float newDist = spacing(event);
				// if (newDist > 10f) {
				// matrix.set(savedMatrix);
				// float scale = newDist / oldDist;
				// matrix.postScale(scale, scale, mid.x, mid.y);
				// }
				// }
				break;
			}

			view.setImageMatrix(matrix);

			CheckScale(); // 限制缩放范围
			center(); // 居中控制

			return true;
		}

		// 两点的距离
		private float spacing(MotionEvent event) {
			float x = event.getX(0) - event.getX(1);
			float y = event.getY(0) - event.getY(1);
			return FloatMath.sqrt(x * x + y * y);
		}

		// 两点的中点
		private void midPoint(PointF point, MotionEvent event) {
			float x = event.getX(0) + event.getX(1);
			float y = event.getY(0) + event.getY(1);
			point.set(x / 2, y / 2);

		}

		// 限制最大最小缩放比例
		protected void CheckScale() {
			float p[] = new float[9];
			matrix.getValues(p);
			if (mode == ZOOM) {
				if (p[0] < minScaleR) {
					matrix.setScale(minScaleR, minScaleR);
				}
				if (p[0] > maxScaleR) {
					matrix.set(savedMatrix);
				}
			}
		}

		// 自动居中 左右及上下都居中
		protected void center() {
			center(true, true);
		}

		private void center(boolean horizontal, boolean vertical) {
			Matrix m = new Matrix();
			m.set(matrix);
			RectF rect = new RectF(0, 0, bitmap.getWidth(), bitmap.getHeight());
			m.mapRect(rect);
			float height = rect.height();
			float width = rect.width();
			float deltaX = 0, deltaY = 0;
			if (vertical) {
				// int screenHeight = dm.heightPixels; //手机屏幕分辨率的高度
				int screenHeight = (int) (240 * minScaleR);
				if (height < screenHeight) {
					deltaY = (screenHeight - height) / 2 - rect.top;
				} else if (rect.top > 0) {
					deltaY = -rect.top;
				} else if (rect.bottom < screenHeight) {
					deltaY = view.getHeight() - rect.bottom;
				}
			}

			if (horizontal) {
				// int screenWidth = dm.widthPixels; //手机屏幕分辨率的宽度
				int screenWidth = (int) (320 * minScaleR);
				if (width < screenWidth) {
					deltaX = (screenWidth - width) / 2 - rect.left;
				} else if (rect.left > 0) {
					deltaX = -rect.left;
				} else if (rect.right < screenWidth) {
					deltaX = screenWidth - rect.right;
				}
			}
			matrix.postTranslate(deltaX, deltaY);
		}
	}

	@Override
	protected void saveStatus() {
		finish();
	}
}
